package com.component.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.component.domain.MSearchLog;
import com.component.service.MSearchLogService;
import com.component.mapper.MSearchLogMapper;
import com.system.security.domain.SelfUserEntity;
import com.system.util.RequestUtils;
import com.system.util.SecurityUtil;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class MSearchLogServiceImpl extends ServiceImpl<MSearchLogMapper, MSearchLog>
    implements MSearchLogService{

    @Override
    public void addKeyword(String keyword) {
        SelfUserEntity userEntity=SecurityUtil.getUserInfo();
        MSearchLog mSearchLog = new MSearchLog();
        if(userEntity==null){
            mSearchLog.setUserName("匿名用户");
        }else {
            mSearchLog.setUserName(userEntity.getUsername());
        }
        String ip=getIP();
        mSearchLog.setIpAddr(ip);
        mSearchLog.setKeyword(keyword);
        this.save(mSearchLog);
    }

    @Override
    public List<Map<String, Object>> history() {
        String ip = getIP();
        LambdaQueryWrapper<MSearchLog> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(MSearchLog::getKeyword);
        lambdaQueryWrapper.eq(MSearchLog::getIpAddr,ip);
        lambdaQueryWrapper.orderByDesc(MSearchLog::getCreateTime);
        List<Map<String,Object>> mapList=this.baseMapper.selectMaps(lambdaQueryWrapper);
        return mapList;
    }


    private String getIP(){
        HttpServletRequest request = RequestUtils.getHttpServletRequest();
        return RequestUtils.getRemoteAddr(request);
    }




}




